package com.feng.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.feng.Exception.SystemException;
import com.feng.domain.ResponseResult;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.service.UploadService;
import com.feng.util.ConstantPropertiesUtils;
import com.feng.util.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;

@Service
//@ConfigurationProperties(prefix = "oss")
@ConfigurationProperties(prefix = "aliyun.oss.file")
@Data
public class UploadServiceImpl implements UploadService {

    private String accessKey;

    private String secretKey;

    private String bucket;
    private String endpoint;
    private String accessKeySecret;
    private String accessKeyId;
    private String bucketName;
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //判断文件类型,获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断
        if(!originalFilename.endsWith(".png")){
            throw new SystemException(AppHttpCodeEnum.FILETYPEERROR);
        }


        //如果判断通过，上传文件到oss
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url=uploadOss(img,filePath);
        //2099/2/3/UUID.png

        return ResponseResult.okResult(url);
    }

    @Override
    public ResponseResult uploadImgs(MultipartFile file) {
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId= ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret=ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;
        OSS ossClient=null;
        try{
            //创建OSS实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件流
            InputStream inputStream=file.getInputStream();
            //调用oss方法实现上传
            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            //在文件名称添加随机唯一的值
            //对原始文件名进行判断
            if(!originalFilename.endsWith(".png")){
                throw new SystemException(AppHttpCodeEnum.FILETYPEERROR);
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //最新文件名称
            String newFileName=uuid+originalFilename;
            //将文件按照日期分类
            //2023/1/10/asdasdas01.jpg
            //获取当前日期
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            newFileName=dataPath+"/"+newFileName;
            ossClient.putObject(bucketName,newFileName,inputStream);
            //把文件上传路径返回手动拼接回来
            //  https://edu-202323.oss-cn-guangzhou.aliyuncs.com/0E496F4649E354C0B12993C03903620B.png
            String url="https://"+bucketName+"."+endpoint+"/"+newFileName;
            return ResponseResult.okResult(url);

        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_ERROR);
        }
        finally {
            //关闭
            ossClient.shutdown();
        }

    }


    private String uploadOss(MultipartFile imgFile,String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "a0Bqa1KNYAhp1rlRaTo0x3vhRFphI8RK4XrL__Qu";
//        String secretKey = "AQhRLHGIifbGcd-bkMlgM-zhmy3v26Tv7ZPzy6gC";
//        String bucket = "fg-blog";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
//            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            InputStream inputStream=imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);


            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://rjmh9izhw.hn-bkt.clouddn.com/"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "http://rjmh9izhw.hn-bkt.clouddn.com/"+key;
    }
}
